package cn.yll.order.controller;


import cn.yll.api.order.request.CashOrderRequest;
import cn.yll.api.order.request.OrderLineRequest;
import cn.yll.api.order.request.OrderRequest;
import cn.yll.api.order.response.OrderResponse;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import cn.yll.common.module.RestModel;
import cn.yll.common.utils.CopierUtil;
import cn.yll.api.util.RestUtil;
import cn.yll.order.business.GoodBusiness;
import cn.yll.order.entity.OrderLinesEntity;
import cn.yll.order.entity.OrdersEntity;
import cn.yll.order.service.IOrderLinesService;
import cn.yll.order.service.IOrdersService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


/**
 * <p>
 * 用户订单表 前端控制器
 * </p>
 *
 * @author yll
 * @since 2022-08-03
 */
@RestController
@Api(tags = "用户订单表相关接口")
@RequestMapping("/orders")
public class OrdersController extends BaseController {

    @Autowired
    private GoodBusiness goodBusiness;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IOrderLinesService linesService;

    @PostMapping("createOrder")
    @ApiOperation(value = "用户下单接口")
    @Transactional(rollbackFor = Exception.class)
    public RestModel<OrderResponse> createOrder(@RequestBody OrderRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getUserId()) || CollectionUtils.isEmpty(request.getLines())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        //扣减商品库存
        goodBusiness.checkPriceAndReduceNum(request.getLines());
        int totalCost = 0;
        List<OrderLineRequest> lines = request.getLines();
        List<OrderLinesEntity> linesEntities = new ArrayList<>(request.getLines().size());
        for (int i = 1; i <= lines.size(); i++) {
            OrderLineRequest line = lines.get(i - 1);
            if (Objects.isNull(line.getGoodId()) || Objects.isNull(line.getBuyNum()) || Objects.isNull(line.getPrice())) {
                return RestUtil.error(BsErrEnum.PARAM_EMPTY);
            }
            int lineCost = line.getBuyNum() * line.getPrice();
            totalCost += lineCost;
            OrderLinesEntity linesEntity = new OrderLinesEntity();
            linesEntity.setLineNum(i).setGoodNum(line.getBuyNum()).setGoodId(line.getGoodId()).setPrice(line.getPrice()).setTotalCost(lineCost);
            linesEntities.add(linesEntity);
        }
        OrdersEntity order = new OrdersEntity();
        order.setUserId(request.getUserId());
        order.setTotalCost(totalCost);
        //订单状态 0新建 10已支付 20已完成 30已取消
        order.setBizStatus(0);
        //生成待支付订单
        boolean result = ordersService.save(order);
        if (!result) {
            throw new BsException(BsErrEnum.REQUEST_ERROR, "创建订单异常");
        }
        linesEntities.forEach(e-> e.setOrderId(order.getId()));
//        踩坑记录！！！！！！！mybatis-plus这个方法不支持seata分布式事务回滚
//        linesService.saveBatch(linesEntities);
        // 创建订单行记录
        int row = linesService.saveBatch(linesEntities);
        if (row == 0) {
            throw new BsException(BsErrEnum.REQUEST_ERROR, "创建订单行异常");
        }
        return RestUtil.sucess(CopierUtil.convertT(order, OrderResponse.class));
    }

    @PostMapping("cashOrder")
    @ApiOperation(value = "用户下单接口")
    public RestModel<?> cashOrder(@RequestBody CashOrderRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getOrderId()) || Objects.isNull(request.getUserId()) || Objects.isNull(request.getTotalCost())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }

        OrdersEntity order = new OrdersEntity();
        order.setId(request.getOrderId());
        order.setUserId(request.getUserId());
        order.setTotalCost(request.getTotalCost());
        //订单状态 0新建 10已支付 20已完成 30已取消
        order.setBizStatus(10);
        boolean result = ordersService.lambdaUpdate().eq(OrdersEntity::getId, request.getOrderId())
                .eq(OrdersEntity::getBizStatus, 0)
                .eq(OrdersEntity::getUserId, request.getUserId())
                .eq(OrdersEntity::getTotalCost, request.getTotalCost())
                .set(OrdersEntity::getBizStatus, 10)
                .update();
        if (result) {
            return RestUtil.sucess(CopierUtil.convertT(order, OrderResponse.class));
        }

        throw new BsException(BsErrEnum.REQUEST_ERROR, "订单已支付或不存在");
    }
}
